package com.dhecp.project.hr.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.service.UpdateLogService;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.hr.domain.AmazonRegion;
import com.dhecp.project.hr.domain.AmazonRegionItem;
import com.dhecp.project.hr.domain.AmazonShop;
import com.dhecp.project.hr.mapper.AmazonRegionItemMapper;
import com.dhecp.project.hr.mapper.AmazonRegionMapper;
import com.dhecp.project.hr.mapper.AmazonShopMapper;
import com.dhecp.project.hr.service.AmazonShopService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: kjecp
 * @description: 网店资料 服务层
 * @author: hlf
 * @create: 2022-09-22 14:27
 */
@Service
public class AmazonShopServiceImpl extends BaseModuleServiceImpl implements AmazonShopService {

    @Autowired
    private AmazonShopMapper businessMapper;

    @Autowired
    private AmazonRegionMapper amazonRegionMapper;
    @Autowired
    private AmazonRegionItemMapper amazonRegionItemMapper;

    @Autowired
    private UpdateLogService updateLogService;
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    /**
     * 查询
     *
     * @param params
     * @return List - AttendanceQJ
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<AmazonShop> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句

//        String otherWhereStr = "";
//        if ((params.get("otherWhere") == null || params.get("otherWhere") == "") && ShiroUtils.getMandatorLevel() < 6){
//            otherWhereStr = "C1.CUser = '" + ShiroUtils.getMandatorId() + "'";
//        }
//
//        if (!"".equals(otherWhereStr)){
//            params.put("otherWhereStr", otherWhereStr);
//        }

        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "createTime asc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return businessMapper.select(params);
    }

    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.AmazonShop
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public AmazonShop findByGuid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return businessMapper.findById(params);
    }

    /**
     *@Description: 通过店铺名称查询
     */
    @Override
    public AmazonShop findByShopName(String shopName) {
        return businessMapper.findByShopName(shopName);
    }


    /**
     * 保存
     *
     * @param moduleTable 必要参数：功能唯一标识
     * @param infoMap     必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @param infoItems   必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author DH-Xxj
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        AmazonShop oldData = new AmazonShop();
        AmazonShop amazonShop = JSON.parseObject(params.get("infoItems").toString(), AmazonShop.class);

        Map<String, Object> params2 = new HashMap<String, Object>();
        params2.put("guid", amazonShop.getGuid());
        oldData = businessMapper.findById(params2);

        if (amazonShop.getGuid() != null && !amazonShop.getGuid().equals("")) {
            amazonShop.setUpdateTime(new Date());
            amazonShop.setUpdateUser(ShiroUtils.getUserId());
            businessMapper.update(amazonShop);
            updateLogService.addUpdateLog(params.get("moduleTable").toString(), amazonShop.getGuid(), oldData, amazonShop, "修改");
        } else {

            AmazonShop amazonShopSellerId = businessMapper.findByShopSellerId(amazonShop.getSellerId());
            if (amazonShopSellerId != null && Objects.equals(amazonShopSellerId.getSellerId(), amazonShop.getSellerId())){
                return AjaxResult.error("该卖家已存在，不可重复添加！");
            }

            if (amazonShop.getMarketplaceIds().split(",").length > 1) {
                List<String> ids = new ArrayList<>();
                List<String> names = new ArrayList<>();
                List<String> codes = new ArrayList<>();

                ids = Arrays.asList(amazonShop.getMarketplaceIds().split(","));
                names = Arrays.asList(amazonShop.getCountryName().split(","));
                codes = Arrays.asList(amazonShop.getCountryCode().split(","));

                for (int i = 0; i < ids.size(); i++) {
                    AmazonShop amazonShop2 = new AmazonShop();
                    amazonShop2.setGuid(RandomValueUtils.getGUID());
                    amazonShop2.setCreateTime(new Date());
                    amazonShop2.setCreateUser(ShiroUtils.getUserId());
                    amazonShop2.setAuthorizeState("未授权");
                    amazonShop2.setAuthorizeStateGg("未授权");
                    amazonShop2.setCompanyID(amazonShop.getCompanyID());
                    amazonShop2.setCompanyName(amazonShop.getCompanyName());
                    amazonShop2.setOriginalShopUser(amazonShop.getShopUser());
                    amazonShop2.setShopUser(amazonShop.getShopUser()+"-"+codes.get(i));
                    amazonShop2.setShopName(amazonShop.getShopName()+"-"+codes.get(i));
                    amazonShop2.setMarketplaceIds(ids.get(i));
                    amazonShop2.setCountryName(names.get(i));
                    amazonShop2.setSellerId(amazonShop.getSellerId());
                    amazonShop2.setRegionName(amazonShop.getRegionName());
                    amazonShop2.setRegionGuid(amazonShop.getRegionGuid());
                    if (amazonShop.getRegionName().equals("北美")){
                        amazonShop2.setRegionCode("NORTH");
                    } else  if (amazonShop.getRegionName().equals("欧洲")){
                        amazonShop2.setRegionCode("EUROPE");
                    } else if (amazonShop.getRegionName().equals("远东")) {
                        amazonShop2.setRegionCode("ASIA");
                    }

                    businessMapper.insert(amazonShop2);
                }
            } else {
                amazonShop.setGuid(RandomValueUtils.getGUID());
                amazonShop.setCreateTime(new Date());
                amazonShop.setCreateUser(ShiroUtils.getUserId());
                amazonShop.setAuthorizeState("未授权");
                amazonShop.setAuthorizeStateGg("未授权");
                amazonShop.setOriginalShopUser(amazonShop.getShopUser());
                amazonShop.setShopUser(amazonShop.getShopUser()+"-"+amazonShop.getCountryCode());
                amazonShop.setShopName(amazonShop.getShopName()+"-"+amazonShop.getCountryCode());
                businessMapper.insert(amazonShop);
            }
            updateLogService.addInsertLog(params.get("moduleTable").toString(), amazonShop.getGuid(), "新增");
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), amazonShop.getGuid());
    }

    /**
     * 删除
     *
     * @param params
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<AmazonShop> businessDataList = JSON.parseArray(params.get("infoItems").toString(), AmazonShop.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (AmazonShop businessData : businessDataList) {
            businessMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }


    /**
     * 查询 地区 国家
     *
     * @param params
     * @return List - AmazonRegion
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<AmazonRegion> queryRegionList(Map<String, Object> params) throws Exception {
        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "createTime asc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return amazonRegionMapper.select(params);
    }

    @Override
    public List<AmazonRegionItem> queryRegionItemList(Map<String, Object> params) throws Exception {
        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "createTime asc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return amazonRegionItemMapper.selectlist(params);
    }
}